<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="缴费类型" prop="paymentType" >
        <el-select v-model="queryParams.paymentType"  style="width: 160px"  placeholder="请选择缴费类型" clearable>
          <el-option label="水费" value="0"></el-option>
          <el-option label="电费" value="1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="缴费金额" prop="paymentPrice">
        <el-input
            v-model="queryParams.paymentPrice"
            placeholder="请输入缴费金额"
            clearable
            @keyup.enter="handleQuery"
        />
      </el-form-item>




<!--      <el-form-item label="缴费业主ID" prop="paymentUser">-->
<!--        <el-input-->
<!--            v-model="queryParams.paymentUser"-->
<!--            placeholder="请输入缴费业主ID"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="缴费方式" prop="paymentWay" >
        <el-select v-model="queryParams.paymentWay" placeholder="请选择缴费方式" clearable  style="width: 150px">
          <el-option label="支付宝" value="支付宝"></el-option>
          <el-option label="微信" value="微信"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="缴费时间" prop="paymentTime">
        <el-date-picker clearable
                        v-model="queryParams.paymentTime"
                        type="date"
                        value-format="YYYY-MM-DD"
                        placeholder="请选择缴费时间">
        </el-date-picker>
      </el-form-item>
<!--      <el-form-item label="缴费详情" prop="paymentDetail">-->
<!--        <el-input-->
<!--            v-model="queryParams.paymentDetail"-->
<!--            placeholder="请输入缴费详情"-->
<!--            clearable-->
<!--            @keyup.enter="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['payment:pay:add']"
        >新增</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="danger"
            plain
            icon="Delete"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['payment:pay:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['payment:pay:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="payList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="主键ID" align="center" prop="id" />-->


      <el-table-column label="楼栋名称" align="center" prop="buildingName" />
      <el-table-column label="房间号" align="center" prop="roomNo" />
<!--      <el-table-column label="缴费业主ID" align="center" prop="paymentUser" />-->
      <el-table-column label="业主姓名" align="center" prop="userName" />

      <el-table-column label="缴费方式" align="center" prop="paymentWay">

      </el-table-column>
      <el-table-column label="缴费类型" align="center" prop="paymentType">
        <template #default="scope">
          <span>{{ scope.row.paymentType === 0 ? '水费' : '电费' }}</span>
        </template>
      </el-table-column>

      <el-table-column label="缴费金额" align="center" prop="paymentPrice" />
      <el-table-column label="缴费时间" align="center" prop="paymentTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.paymentTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="缴费状态" align="center" prop="paymentStatus">
        <template #default="scope">
          <el-tag :type="scope.row.paymentStatus === 0 ? 'warning' : 'success'">
            {{ scope.row.paymentStatus === 0 ? '待缴费' : '已缴费' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="paymentDetail" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['payment:pay:remove']">删除</el-button>
<!--          <el-button link type="success" icon="Wallet" @click="handlePay(scope.row)" v-hasPermi="['payment:pay:pay']">去支付</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />

    <!-- 添加或修改缴费对话框 -->
    <!-- 添加或修改缴费对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>

      <el-form ref="payRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="楼栋名称" prop="buildingId">
          <el-select
              v-model="form.buildingId"
              placeholder="请选择楼栋"
              @change="handleBuildingChange">
            <el-option
                v-for="building in buildingList"
                :key="building.id"
                :label="building.buildingName"
                :value="building.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="房间号" prop="roomId">
          <el-select
              v-model="form.roomId"
              placeholder="请选择房间号"
              :disabled="!form.buildingId">
            <el-option
                v-for="room in roomOptions"
                :key="room.id"
                :label="room.roomNo"
                :value="room.id">
            </el-option>
          </el-select>
        </el-form-item>
<!--        <el-form-item label="业主姓名" prop="userName">-->
<!--          <el-input v-model="form.userName" placeholder="请选择楼栋和房间号自动填充" disabled />-->
<!--        </el-form-item>-->

        <el-form-item label="缴费类型" prop="paymentType">
          <el-select v-model="form.paymentType" placeholder="请选择缴费类型">
            <el-option label="水费" value=0></el-option>
            <el-option label="电费" value=1></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="缴费金额" prop="paymentPrice">
          <el-input v-model="form.paymentPrice" placeholder="请输入缴费金额" />
        </el-form-item>
<!--        <el-form-item label="缴费业主ID" prop="paymentUser">-->
<!--          <el-input v-model="form.paymentUser" placeholder="请输入缴费业主ID" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="缴费方式" prop="paymentWay">-->
<!--          <el-select v-model="form.paymentWay" placeholder="请选择缴费方式">-->
<!--            <el-option label="支付宝" value="支付宝"></el-option>-->
<!--            <el-option label="微信" value="微信"></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="缴费时间" prop="paymentTime">-->
<!--          <el-date-picker clearable-->
<!--                          v-model="form.paymentTime"-->
<!--                          type="date"-->
<!--                          value-format="YYYY-MM-DD"-->
<!--                          placeholder="请选择缴费时间">-->
<!--          </el-date-picker>-->
<!--        </el-form-item>-->
        <el-form-item label="备注" prop="paymentDetail">
          <el-input v-model="form.paymentDetail" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Pay">
import request from '@/utils/request'//去支付1
import { listPay, getPay, delPay, addPay, updatePay } from "@/api/payment/pay"

// 2025-09-24: 引入楼栋和房间管理API
import { listBuildingManage } from "@/api/behindBuilding/buildingManage"
import {getRoomIdsByBuildingIdAndBindStatus, listRoomManage, getRoomNoById } from "@/api/behindRoom/roomManage"

// 2025-09-24: 添加楼栋和房间相关变量
const buildingList = ref([])  // 楼栋列表
const roomOptions = ref([])   // 房间选项列表（只包含通过getRoomNoById获取的数据）

const { proxy } = getCurrentInstance()

const payList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    paymentType: null,
    paymentPrice: null,
    paymentUser: null,
    paymentWay: null,
    paymentTime: null,
    paymentStatus: null,
    paymentDetail: null
  },
  rules: {
    paymentType: [
      { required: true, message: "缴费类型不能为空", trigger: "change" }
    ],
    paymentPrice: [
      { required: true, message: "缴费金额不能为空", trigger: "blur" }
    ],
    buildingId: [
      { required: true, message: "楼栋名称不能为空", trigger: "change" }
    ],
    roomId: [
      { required: true, message: "房间号不能为空", trigger: "change" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

/** 查询缴费列表 */
function getList() {
  loading.value = true
  listPay(queryParams.value).then(response => {
    payList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 2025-09-25 01:20:00: 添加获取楼栋列表的方法
/** 查询楼栋列表 */
function getBuildingList() {
  return listBuildingManage({}).then(response => {
    buildingList.value = response.rows
  })
}

// 2025-09-25 02:30:00: 根据楼栋ID获取其中绑定状态为1的房屋列表
/** 根据楼栋ID获取其中绑定状态为1的房屋列表 */
function getBoundRoomListByBuildingId(buildingId) {
  // 2025-09-25 02:30:00: 清空房间选项列表
  roomOptions.value = []
  form.value.roomId = null

  if (!buildingId) {
    return Promise.resolve()
  }

  // 2025-09-25 02:30:00: 调用API方法获取绑定状态为1的房间ID列表
  return getRoomIdsByBuildingIdAndBindStatus(buildingId).then(response => {
    // 2025-09-25 02:30:00: 获取到房间ID列表后，遍历调用getRoomNoById获取房间号
    if (response.code === 200) {
      const roomIds = response.data;
      if (roomIds && roomIds.length > 0) {
        // 2025-09-25 02:30:00: 创建获取房间号的Promise数组
        const promises = roomIds.map(id => {
          return getRoomNoById(id).then(res => {
            if (res.code === 200) {
              // 2025-09-25 02:30:00: 构造房间选项对象，只使用getRoomNoById返回的data字段
              return {
                id: id,
                roomNo: res.data  // 只使用getRoomNoById接口返回的data字段作为房间号
              };
            } else {
              proxy.$modal.msgError(`获取房间号失败: ${res.msg || '未知错误'}`);
              return null;
            }
          }).catch(error => {
            proxy.$modal.msgError("获取房间号失败");
            console.error(error);
            return null;
          });
        });

        // 2025-09-25 02:30:00: 等待所有Promise完成
        return Promise.all(promises);
      }
    } else {
      proxy.$modal.msgError(response.msg || "获取房间列表失败");
      return Promise.reject();
    }
  }).then(results => {
    // 2025-09-25 02:30:00: 过滤掉获取失败的项，并更新房间选项列表
    if (results) {
      roomOptions.value = results.filter(item => item !== null);
    }
  }).catch(error => {
    proxy.$modal.msgError("获取房间列表失败");
    console.error(error);
  });
}

// 2025-09-25 01:20:00: 添加楼栋选择变化时的处理方法
/** 楼栋选择变化时触发 */
function handleBuildingChange(buildingId) {
  // 2025-09-25 01:20:00: 当楼栋选择变化时，调用 getBoundRoomListByBuildingId 获取该楼栋下的已绑定房间
  getBoundRoomListByBuildingId(buildingId)
}






// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    paymentType: null,
    paymentPrice: null,
    buildingId: null,
    buildingName: null,  // 2025-09-24: 添加楼栋名称字段
    roomId: null,
    paymentUser: null,
    paymentWay: null,
    paymentTime: null,
    paymentStatus: null,
    paymentDetail: null
  }
  // 2025-09-25 02:30:00: 重置时清空房间选项列表
  roomOptions.value = []
  proxy.resetForm("payRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id)
  single.value = selection.length != 1
  multiple.value = !selection.length
}

// 2025-09-25 01:30:00: 更新新增按钮操作，只获取楼栋数据
/** 新增按钮操作 */
function handleAdd() {
  reset()
  // 2025-09-25 01:30:00: 获取楼栋数据
  getBuildingList().then(() => {
    open.value = true
    title.value = "添加缴费"
  })
}

// 2025-09-25 01:30:00: 更新修改按钮操作，添加楼栋和房间数据获取
/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id || ids.value
  getPay(_id).then(response => {
    form.value = response.data
    // 2025-09-25 01:30:00: 获取楼栋数据
    return getBuildingList()
  }).then(() => {
    // 2025-09-25 01:30:00: 设置房间列表
    if (form.value.buildingId) {
      return getBoundRoomListByBuildingId(form.value.buildingId)
    }
  }).then(() => {
    open.value = true
    title.value = "修改缴费"
  })
}


/** 提交按钮 */

// 2025-09-25 01:30:00: 提交按钮，自动填充楼栋名称和房间号
/** 提交按钮 */
function submitForm() {
  proxy.$refs["payRef"].validate(valid => {
    if (valid) {
      // 2025-09-25 01:30:00: 查找并添加楼栋名称和房间号
      if (form.value.buildingId) {
        const selectedBuilding = buildingList.value.find(building => building.id === form.value.buildingId)
        if (selectedBuilding) {
          form.value.buildingName = selectedBuilding.buildingName
        }
      }

      if (form.value.roomId) {
        const selectedRoom = roomOptions.value.find(room => room.id === form.value.roomId)
        if (selectedRoom) {
          form.value.roomNo = selectedRoom.roomNo
        }
      }

      if (form.value.id != null) {
        updatePay(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addPay(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}




/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value
  proxy.$modal.confirm('是否确认删除缴费编号为"' + _ids + '"的数据项？').then(function() {
    return delPay(_ids)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}
// ... existing code ...
/** 导出按钮操作 */
// ... existing code ...
/** 导出按钮操作 */
// ... existing code ...
/** 导出按钮操作 */
// 存储订单的uniqueCode映射
const orderCodeMap = new Map()

// 去支付 - 支付按钮操作
function handlePay(row) {
  let uniqueCode = orderCodeMap.get(row.id)

  // 如果该订单还没有生成uniqueCode，则生成一个新的并保存
  if (!uniqueCode) {
    // 根据订单ID生成唯一的uniqueCode
    uniqueCode = btoa(row.id.toString()).replace(/[^a-zA-Z0-9]/g, '').substr(0, 16)
    // 如果转换后的字符串不足16位，则在末尾补随机字符
    if (uniqueCode.length < 16) {
      const randomPart = Math.random().toString(36).substr(2, 16 - uniqueCode.length)
      uniqueCode += randomPart
    }
    // 保存该订单的uniqueCode
    orderCodeMap.set(row.id, uniqueCode)
  }

  // 去支付 - 构造支付请求参数
  const payRequest = {
    orderId: row.id,
    uniqueCode: uniqueCode
  }

  // 去支付 - 发送支付请求
  request({
    url: '/payment/pay/payZfb',
    method: 'post',
    data: payRequest,
    responseType: 'text'
  }).then(response => {
    // 去支付 - 创建临时页面并提交表单跳转到支付宝（新窗口打开）
    const newWindow = window.open('', '_blank')
    if (newWindow) {
      newWindow.document.write(response)
      newWindow.document.close()
    } else {
      // 如果无法打开新窗口，则在当前窗口打开
      document.write(response)
      document.close()
    }
  }).catch((error) => {
    proxy.$modal.msgError("支付请求失败")
  })
}
// ... existing code ...

getList()
</script>
